/**
 * Copyright 厦门中软海晟信息技术有限公司 版权所有 违者必究 2019
 */
package com.opencvjava.lessons2;

import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfFloat;
import org.opencv.core.MatOfInt;
import org.opencv.imgproc.Imgproc;
import org.springframework.stereotype.Service;

import java.util.Arrays;

import static com.opencvjava.support.util.CvUtils.imshow;
import static com.opencvjava.support.util.CvUtils.mat;
import static org.opencv.core.CvType.CV_8UC1;
import static org.opencv.imgproc.Imgproc.COLOR_BGR2HSV;
import static org.opencv.imgproc.Imgproc.calcBackProject;
import static org.opencv.imgproc.Imgproc.calcHist;
import static org.opencv.imgproc.Imgproc.cvtColor;

/**
 * @author : sunzb(sunzb@hsit.com.cn)
 * @date: 2019/1/14
 */
@Service
public class HistBackProjectDemo {
    public void test() {
        Mat src = mat("backProject", "target.png");
        Mat sample = mat("backProject", "sample.png");
        if (src.empty() || sample.empty()) {
            throw new RuntimeException("图片读取失败");
        }
        imshow("源图", src);
        imshow("模型图像", sample);
        Mat hsv = new Mat();
        cvtColor(sample, hsv, COLOR_BGR2HSV);
        Mat mHist = new Mat();
        Mat mask = Mat.ones(sample.size(), CV_8UC1);
        calcHist(Arrays.asList(hsv), new MatOfInt(0, 1), mask, mHist,
                new MatOfInt(30, 32), new MatOfFloat(0, 179, 0, 255));

        Mat srcHsv = new Mat();
        cvtColor(src, srcHsv, COLOR_BGR2HSV);

        Mat dst = new Mat();
        calcBackProject(Arrays.asList(srcHsv), new MatOfInt(0, 1), mHist, dst,
                new MatOfFloat(0, 179, 0, 255), 1);
        Core.normalize(dst, dst, 0, 255, Core.NORM_MINMAX);
        imshow("结果", dst);
    }
}
